package alone.redis.queue.redisqueue.service;

import alone.redis.queue.redisqueue.util.RedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/**
 * redis订阅发布模式订阅者
 */
public class MessageSubscribe implements Runnable {

    private static final String channelName = "channel:publish";

    private MyJedisSub myJedisSub = new MyJedisSub();

    @Override
    public void run() {
        for (;;){
            subscribeMessage();
        }
    }

    private void subscribeMessage(){
        Jedis jedis = RedisUtil.getJedis();
        //第一个参数为处理接收消息的实现类  第二个参数为订阅频道
        jedis.subscribe(myJedisSub,channelName);
    }


    public static void main(String[] args) {
        MessageSubscribe messageSubscribe = new MessageSubscribe();
        Thread thread1 = new Thread(messageSubscribe,"thread1");
        Thread thread2 = new Thread(messageSubscribe,"thread2");
        Thread thread3 = new Thread(messageSubscribe,"thread3");
        thread1.start();
        thread2.start();
        thread3.start();
    }


    static class MyJedisSub extends JedisPubSub {
        @Override
        public void onMessage(String channel, String message) {
            System.out.println(Thread.currentThread().getName() + " getMessage: channel=" + channel + " message=" + message);
            if ("exit".equals(message)){
                System.exit(0);
            }
        }
    }

}
